package pl.edu.pw.ws.dao.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import pl.edu.pw.ws.dao.OfferDAO;
import pl.edu.pw.ws.model.Address;
import pl.edu.pw.ws.model.Offer;

@Repository("offerDAO")
public class MySQLOfferDAO implements OfferDAO {
	
	private static final String GET_OFFER = "select * from offers where offer_id = ?";
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public Offer getOffer(String offerId) {
		Offer offer = null; 
	        try {
	        	offer = (Offer) jdbcTemplate.queryForObject(GET_OFFER, new Object [] {offerId}, new RowMapper<Object>() {
	                
	                @Override
	                public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
	                    Offer offer = new Offer();
	                    offer.setOfferId(Integer.toString(rs.getInt("offer_id")));
	                    offer.setTitle(rs.getString("title"));
	                    offer.setDescription(rs.getString("description"));
	                    Address address = new Address();
	                    address.setCity(rs.getString("city"));
	                    address.setStreet(rs.getString("street"));
	                    offer.setAddress(address);
	                    return offer;
	                }
	            });
	        }catch(EmptyResultDataAccessException ex) {
	            System.err.println("No offer registered for offerId: " + offerId);
	            ex.printStackTrace();
	        }
		
		return offer;
	}

}
